package com.smart.speaker.config;

import com.alibaba.dashscope.audio.tts.SpeechSynthesizer;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SpeechSynthesizerConfig {

    @Value("${ali.dashscope.synthesizer.pool}")
    private int poolSize;

    @Bean(name = "speechSynthesizerGenericObjectPool")
    public GenericObjectPool<SpeechSynthesizer> speechSynthesizerGenericObjectPool() {
        SpeechSynthesizerConfig.SpeechSynthesizerObjectFactory factory = new SpeechSynthesizerConfig.SpeechSynthesizerObjectFactory();
        GenericObjectPoolConfig<SpeechSynthesizer> config = new GenericObjectPoolConfig<>();
        config.setMaxTotal(poolSize);
        config.setMaxIdle(poolSize);
        config.setMinIdle(poolSize);
        return new GenericObjectPool<>(factory, config);
    }

    public static class SpeechSynthesizerObjectFactory extends BasePooledObjectFactory<SpeechSynthesizer> {

        public SpeechSynthesizerObjectFactory() {
            super();
        }
        @Override
        public SpeechSynthesizer create() {
            return new SpeechSynthesizer();
        }

        @Override
        public PooledObject<SpeechSynthesizer> wrap(SpeechSynthesizer obj) {
            return new DefaultPooledObject<>(obj);
        }
    }
}
